<template>
  <div class="container">
    <div class="app-container">
      <div style="padding:10px">
        <el-button type="primary" size="mini" @click="showDialog=true" @close="closeClcik">添加</el-button>
      </div>
      <el-table :data="roleList">
        <el-table-column prop="name" label="角色" align="center" width="200">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center" width="200">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else>{{ row.state===1?"已启用":row.state===0? "未启用":"无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <div v-if="row.isEdit">
              <el-button type="primary" @click="enitRoleClick(row)">确定</el-button>
              <el-button @click="row.isEdit=false">取消</el-button>
            </div>
            <div v-else>
              <el-button type="text" size="mini" @click="permissionClick(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editClick(row)">编辑</el-button>
              <el-popconfirm
                title="确定删除该角色吗？"
                @onConfirm="delRoleClick(row)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height:60px">
        <el-pagination
          :current-page="pageParams.page"
          layout="prev, pager, next"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          @current-change="handCurrent"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <el-form ref="pageForm" :rules="rules" :model="pageForm" label-width="100px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="pageForm.name" style="width: 300px;" size="mini" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch v-model="pageForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="pageForm.description" style="width: 300px;" size="mini" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item>
          <el-row style="width: 300px;">
            <el-button type="primary" @click="roleClick">确认</el-button>
            <el-button @click="closeClcik">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="showPermDialog" @close="close">
      <el-tree
        ref="permTree"
        :data="permList"
        :props="{label:'name'}"
        show-checkbox
        node-key="id"
        default-expand-all
        check-strictly
      />
      <template #footer>
        <el-row>
          <el-button type="primary" size="mini" @click="permConfirClick">确定</el-button>
          <el-button size="mini" @click="close">取消</el-button>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleListAPI,
  assignPermissionAPI,
  setRoleListAPI,
  getRoleAPI,
  delRoleAPI,
  getRoleDetailAPI
} from '@/api/role.js'
import { getPermissionListAPI } from '@/api/permission'
import { listToTreeList } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      pageParams: {
        total: 1,
        pagesize: 5,
        page: 1
      },
      showDialog: false,
      pageForm: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [{ required: true, message: '请填写角色名称', trigger: 'blur' }],
        description: [{ required: true, message: '请填写角色信息', trigger: 'blur' }]
        // state: 1
      },
      showPermDialog: false,
      permList: [],
      currentRoleId: null

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    roleClick() {
      this.$refs.pageForm.validate(async(isOK) => {
        if (isOK) {
          await setRoleListAPI(this.pageForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.closeClcik()
        }
      })
    },
    async getRoleList() {
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total
      // 对数组对象进行增加key值，this.$set(要进行操纵的对象，“属性”，属性值)
      // 因为数据传递给子节点了，使用default=“{数据}”把数据从子节点传递回插槽
      // 点击编辑属性值改为true，用v-if绑定isEdit达到切换目的，
      // 因为每个item（换句话说每行数据）都有一个isEdit属性，所以互不影响，可以多行编辑
      this.roleList.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    handCurrent(currentPage) {
      this.pageParams.page = currentPage
      this.getRoleList()
    },
    closeClcik() {
      this.$refs.pageForm.resetFields()
      this.showDialog = false
      if (this.roleList.length === 5) {
        this.pageParams.page++
      }
    },
    editClick(data) {
      data.isEdit = true
      data.editRow.name = data.name
      data.editRow.description = data.description
      data.editRow.state = data.state
    },
    async enitRoleClick(data) {
      if (data.editRow.name && data.editRow.description) {
        await getRoleAPI({ ...data.editRow, id: data.id })
        this.$message.success('角色信息修改成功')
        Object.assign(data, { ...data.editRow, isEdit: false })
      } else {
        this.$message.warning('请填写角色信息')
      }
    // 调用接口，编辑表单修改后提交给后台
    },
    async delRoleClick(obj) {
      await delRoleAPI(obj.id)
      this.$message.success(obj.name + '删除成功')
      this.getRoleList()
      if (this.pageParams.page > 1 && this.roleList.length === 1) {
        this.pageParams.page--
      }
    },
    async permissionClick(id) {
      this.showPermDialog = true
      this.currentRoleId = id
      this.permList = listToTreeList(await getPermissionListAPI(), 0)
      const { permIds } = await getRoleDetailAPI(id)
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },
    close() {
      this.$refs.permTree.setCheckedKeys([])
      this.showPermDialog = false
    },
    async permConfirClick() {
      await assignPermissionAPI({ id: this.currentRoleId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.close()
    }
  }
}
</script>
